<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------
namespace app\staffapi\controller;

use app\Request;
use crmeb\services\CacheService;
use app\services\car\CarStaffService;


/**
 * 管理端授权类
 * Class AuthController
 * @package app\api\controller
 */
class LoginController
{
    protected $services = NUll;

    /**
     * LoginController constructor.
     * @param CarStaffService $services
     */
    public function __construct(CarStaffService $services)
    {
        $this->services = $services;
    }

    /**
     * 账号密码登录
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(Request $request)
    {
        [$login_name, $pwd] = $request->postMore([
            'login_name', 'pwd'
        ], true);

        if (!$login_name || !$pwd) {
            return app('json')->fail('请输入账号和密码');
        }
        return app('json')->success('登录成功', $this->services->login($login_name, $pwd));
    }

    /**
     * 退出登录
     * @param Request $request
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function logout(Request $request)
    {
        $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
        if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版，删除此行，某些服务器无法获取到token调整为 Authori-zation
        CacheService::redisHandler()->delete(md5($token));
        return app('json')->success('退出成功');
    }


    /**
     * 密码修改
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit_password(Request $request)
    {
        [$old_password, $new_password] = $request->postMore([
            'old_password', 'new_password'
        ], true);
        $manager_id =  $request->managerId();
        $res = $this->services->editPassword($manager_id, $old_password, $new_password);
        return app('json')->success('修改密码成功');
    }
}
